﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Jacobi.Seesmic.FeedReader.Model
{
    /// <summary>
    /// Manages a collection of <see cref="TimelineFeedItem"/>s by key (UniqueId).
    /// </summary>
    internal sealed class TimelineFeedItemCollection : KeyedCollection<string, TimelineFeedItem>
    {
        /// <summary>
        /// Returns the <see cref="P:TimelineFeedItem.UniqueId"/> property for the specified <paramref name="item"/>.
        /// </summary>
        /// <param name="item">Can be null.</param>
        /// <returns>Returns null if the <paramref name="item"/> is null.</returns>
        protected override string GetKeyForItem(TimelineFeedItem item)
        {
            if (item != null)
            {
                return item.UniqueId;
            }

            return null;
        }

        /// <summary>
        /// Returns the content of the collection in a sorted order.
        /// </summary>
        public IEnumerable<TimelineFeedItem> Sorted
        {
            get
            {
                var array = new List<TimelineFeedItem>(this).ToArray();

                Array.Sort(array, new TimelineFeedItemComparer());

                return array;
            }
        }

        //---------------------------------------------------------------------

        /// <summary>
        /// Helper class to sort the collection.
        /// </summary>
        private class TimelineFeedItemComparer : IComparer, IComparer<TimelineFeedItem>
        {
            /// <summary>
            /// Compares <paramref name="x"/> to <paramref name="y"/>.
            /// </summary>
            /// <param name="x">Can be null.</param>
            /// <param name="y">Can be null.</param>
            /// <returns>Returns 0 if <paramref name="x"/> is equal to <paramref name="y"/>.</returns>
            public int Compare(object x, object y)
            {
                return Compare((TimelineFeedItem)x, (TimelineFeedItem)y);
            }

            /// <summary>
            /// Compares <paramref name="x"/> to <paramref name="y"/>.
            /// </summary>
            /// <param name="x">Can be null.</param>
            /// <param name="y">Can be null.</param>
            /// <returns>Returns 0 if <paramref name="x"/> is equal to <paramref name="y"/>.</returns>
            public int Compare(TimelineFeedItem x, TimelineFeedItem y)
            {
                if (x != null && y != null)
                {
                    // descending sort
                    return -x.PublishDate.CompareTo(y.PublishDate);
                }

                return 0;
            }
        }
    }
}